<template>
<div class="semCouponList">
  <search-block>
    <template slot="button">
      <el-button type="primary" @click="search(true)">查询</el-button>
      <el-button type="primary" @click="addCoupon">添加优惠券</el-button>
    </template>
    <el-form inline :model="model" label-width="100px" @submit.native.prevent>
      <el-form-item label="优惠券名称:">
        <el-input v-model="model.name"></el-input>
      </el-form-item>
    </el-form>
  </search-block>
  <y-table
    ref="table"
    border
    pagination
    :getDataWay="getDataWay"
    :columns="columns">
    <el-table-column slot="status" label="启用" align="center" header-align="center" width="80">
      <template v-slot="{row}">
        <el-popconfirm
          :title="row.status === '1' ? '是否确认启用该类券？' : '是否确认禁用该类券？'"
          @confirm="() => {
            if(row.status === '1') enable(row)
            else disable(row);
          }"
        >
          <el-switch
            disabled
            slot="reference"
            v-model="row.status"
            active-value="0"
            inactive-value="1"></el-switch>
        </el-popconfirm>
      </template>
    </el-table-column>
    <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="165">
      <template v-slot="{row}">
        <div class="wrap-table-buttons">
          <el-button size="mini" @click="viewCouponItemList(row)">使用情况</el-button>
          <el-button type="primary" size="mini" :disabled="row.total === row.totaled" @click="editPublish(row)">发行</el-button>
          <el-button size="mini" @click="viewCoupon(row)">查看信息</el-button>
          <el-popconfirm
            title="是否确认删除该优惠券？"
            @confirm="delCoupon(row)">
            <el-button slot="reference" type="danger" size="mini">删除</el-button>
          </el-popconfirm>
          <template v-if="row.type === 'SEM_COUPON_SALE_TYPE_EXCHANGE'">
<!--            导出换购券-->
            <div style="width: 80px"></div>
            <el-button size="mini" @click="exportCoupon(row)">导出</el-button>
          </template>
        </div>
      </template>
    </el-table-column>
  </y-table>
  <el-drawer
    :visible.sync="viewForms.showForm"
    :title="viewForms.formTypeTitle[viewForms.formsType]"
    :size="1000"
    destroy-on-close>
    <sem-coupon-item
      :id="viewForms.id"
      @close-drawer="viewForms.showForm = false"
      @refresh="search(true)"></sem-coupon-item>
  </el-drawer>
  <y-form
    ref="yForm"
    v-model="publishForms.formModel"
    :visible.sync="publishForms.showForm"
    :title='"发行优惠券【" + publishForms.formModel.title + "】"'
    destroy-on-close
    width="400px"
    :form-attrs="publishForms.formAttrs"
    :columns="formColumns"
    @ensure="ensureModel">
  </y-form>
  <el-dialog
    :title="`【${itemForms.row.name || '优惠券'}】使用情况`"
    class="force-inner-scroll"
    :visible.sync="itemForms.show"
    @opened="openItemList"
    destroy-on-close
    width="800px">
    <sem-coupon-item-list
      ref="couponItemList"
      :coupon-id="itemForms.row ? itemForms.row.id : ''"
    ></sem-coupon-item-list>
  </el-dialog>
</div>
</template>

<script>
import SemCouponItem from "@/views/sem/semCouponItem/semCouponItem";
import SemCouponItemList from "@/views/sem/semCouponItem/semCouponItemList";
export default {
  name: "semCouponList",
  inject: ['getDictNameSync'],
  components: {SemCouponItem, SemCouponItemList},
  computed:{
    getDataWay(){
      return{
        dataType: 'url',
        data: this.$api.sem.couponPage,
        param: this.model
      }
    },
    formColumns(){
      return [
        {
          label: "过期时间",
          prop: "deadLineDate",
          comp:{
            compType: 'datePicker',
            attrs: {
              type: "date",
              pickerOptions:{
                shortcuts: [{
                  text: '今天',
                  onClick(picker) {
                    picker.$emit('pick', new Date());
                  }
                }]
              },
              valueFormat: 'yyyy-MM-dd'
            }
          }
        },
        {
          label: "发行量(张)",
          prop: "num",
          comp:{
            compType: 'input-number',
            attrs:{
              stepStrictly: true,
              controls: false,
              min: 0,
              max: this.publishForms.formModel.restNum
            }
          }
        }
      ]
    }
  },
  data(){
    return{
      model:{
        name: ''
      },
      columns: [
        {
          label: '名称',
          prop: 'name'
        },
        {
          label: '券所属',
          prop: 'businessType',
          formatter: (function(row){
            return this.getDictNameSync(row.businessType, 'BUSINESS_MODULE');
          }).bind(this)
        },
        {
          label: '券类别',
          prop: 'category',
          formatter: (function(row){
            return this.getDictNameSync(row.category, 'SEM_COUPON_CATEGORY');
          }).bind(this)
        },
        {
          label: '适用人群',
          prop: 'usedScope',
          formatter: (function(row){
            return this.getDictNameSync(row.usedScope, 'SEM_COUPON_SCOPE');
          }).bind(this)
        },
        {
          label: '使用方式',
          prop: 'category',
          formatter(row){
            switch(row.type){
              case 'SEM_COUPON_SALE_TYPE_EXCHANGE':{//换购
                return '换购';
              }
              case 'SEM_COUPON_SALE_TYPE_DEDUCT':{//抵扣
                if(row.rrestrict === '0'){//无限制
                  return `减${row.couponValue}元`;
                }else{
                  return `满${row.restrictValue}元减${row.couponValue}元`;
                }
              }
              case 'SEM_COUPON_SALE_TYPE_DISCOUNT':{//折扣
                if(row.rrestrict === '0'){//无限制
                  return `${row.discountRate}折`;
                }else{
                  return `满${row.restrictValue}元${row.discountRate}折`;
                }
              }
            }
            return '';
          }
        },
        {
          label: '已发行/可发行总量',
          prop: 'total',
          formatter(row){
            return `${row.totaled}张/${row.total}张`
          }
        },
        {
          prop: 'status',
          template: true
        }
      ],
      viewForms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '添加优惠券',
          'EDIT': '查看优惠券'
        },
        id: '',
        showForm: false,
      },
      publishForms:{
        formModel:{
          couponId: '',
          title: '',
          deadLineDate: '',
          num: '',
          restNum: 0
        },
        formAttrs:{
          labelWidth: '100px',
          rules: {
            deadLineDate: [{required: true, message: "请选择有效期", trigger: "change"}]
          }
        },
        showForm: false
      },
      itemForms:{
        row: {},
        show: false
      }
    }
  },
  methods:{
    search(jumpToFirst){
      this.$refs['table'].loadData(this.model, jumpToFirst);
    },
    addCoupon(){
      this.viewForms.formsType = 'ADD';
      this.viewForms.id = '';
      this.viewForms.showForm = true;
    },
    viewCoupon(row){
      this.viewForms.formsType = 'EDIT';
      this.viewForms.id = row.id;
      this.viewForms.showForm = true;
    },
    exportCoupon(row){
      this.$yAxios({
        url: this.$api.sem.exportCouponBatch,
        data:{
          id: row.id
        },
        loading: true
      }, info => {
        if(info?.length){
          let data = [
            ['券编号', '券密码']
          ];
          data.push(...info.map(item => [item.couponItemSn, item.secret]));
          this.$$exportExcel({
            data, fileName: row.name + '.xlsx'
          })
        }else{
          this.$message({
            type: 'warning',
            message: '该批次不存在已发行的券'
          });
        }
      })
    },
    viewCouponItemList(row){
      this.$set(this.itemForms, 'row', row);
      this.itemForms.show = true;
    },
    openItemList(){
      this.$refs['couponItemList'].search(this.itemForms.row.id, true);
    },
    delCoupon(row){
      this.$yAxios({
        url: this.$api.sem.removeCoupon,
        data:{
          ids: [row.id]
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        this.search();
      })
    },
    editPublish(row){
      this.publishForms.formModel.num = 0;
      this.publishForms.formModel.couponId = row.id;
      this.publishForms.formModel.deadLineDate = '';
      this.publishForms.formModel.title = row.name;
      this.publishForms.formModel.restNum = row.total - row.totaled;
      this.publishForms.showForm = true;
    },
    ensureModel(form){
      let newForm = Object.gain(form, ['couponId', 'num', 'deadLineDate']);
      this.$yAxios({
        url: this.$api.sem.publishCoupon,
        data: newForm
      }, info => {
        this.$message({
          type: 'success',
          message: '发行成功'
        });
        this.search();
      })
    },
    enable(row){
      this.$yAxios({
        url: this.$api.sem.enableCoupon,
        data:{
          id: row.id
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: `成功启用【${row.name}】`
        });
        this.search()
      });
    },
    disable(row){
      this.$yAxios({
        url: this.$api.sem.disableCoupon,
        data:{
          id: row.id
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: `成功禁用【${row.name}】`
        });
        this.search()
      });
    }
  }
}
</script>

<style scoped>

</style>